package com.ts.tsjob.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class GetWangBoToken {
    private static final Log log = LogFactory.getLog(HttpsUtils.class);

    private final static String PASSWORD = "1qaz@Wsx";

    private final static String USERID = "13761357208";

    private final static String HOST = "https://bz.shdike.org.cn";

    private final static String GETTOKENURL = "/dfcwgh/ssologin/pcloginbyuser";

    @Cacheable(value = "wangbo_token", unless = "#result == null")
    public String getToken() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        // 构建请求体 (x-www-form-urlencoded格式)
        RequestBody requestBody = new FormBody.Builder()
                .add("password", PASSWORD)
                .add("userid", USERID)
                .build();
        Request request = new Request.Builder()
                .url(HOST+GETTOKENURL)
                .post(requestBody)
                .addHeader("InterfaceType", "App")
                .build();
        String token = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("获取网波token失败：" + response);
            }
            String result = response.body().string();
            JSONObject json = JSONObject.parseObject(result);
            token = json.getJSONObject("data").getString("token");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }
}
